from setting import Setting
import requests
import time
import numpy as np

def requests_(set):
  load_data = []
  try:
    resp = requests.get(set.LOTTO_DOWNLOAD_URL)
    if resp.status_code == 200:
        respJson = resp.json()
        respJson.reverse()
        for i in range(len(respJson)):
          d = respJson[i]
          # load_data.append([d["issueNo"],d["one"],d["two"],d["three"],d["four"],d["five"]])
          # load_data.append([d["one"],d["two"],d["three"],d["four"],d["five"]])
          # load_data.append(d["five"] )
          # 大小类别：0表示小，1表示大
          if d["five"] > 4:
            load_data.append(1)
          else:
            load_data.append(0)
        # print(len(load_data))
        # print(load_data)
        # print(load_data[:10])
        return load_data
    else:
      raise Exception('获取数据失败！')
  except Exception as e:
    print(e)


def getDate(set, shuffle=True):
  load_data = requests_(set)
  x=[]
  y=[]
  total = len(load_data)

  if set.MAX_STEPS >= total: print("错误")
  for item in range(set.MAX_STEPS, total, 1):
    x.append(load_data[item - set.MAX_STEPS:item])
    y.append(load_data[item])
  # print(y)
  # print(x)

  np_x = np.zeros((total-set.MAX_STEPS, set.MAX_STEPS, set.FRONT_VOCAB_SIZE))
  np_y = np.zeros((total-set.MAX_STEPS, set.FRONT_VOCAB_SIZE))

  for i in range(0, len(x), 1):
    # print(i)
    yy = y[i]
    np_y[i][yy] = 1
    for j in range(0, len(x[i]), 1):
      xx = x[i][j]
      np_x[i][j][xx] = 1
      # print(j)

  # print(np_x)
  # print(np_y)

  # 0.8训练。0.2测试。0.1预测测试
  train_data_rate = 0.7
  train_7 = int(train_data_rate * len(x))
  test_1 = int(0.2 * len(x))
  # 打乱训练数据
  if shuffle:
    random_seed = int(time.time())
    # 使用相同的随机数种子，保证x和y的一一对应没有被破坏
    np.random.seed(random_seed)
    np.random.shuffle(np_x)
    np.random.seed(random_seed)
    np.random.shuffle(np_y)

  train_x = np_x[:train_7]
  train_y = np_y[:train_7]
  test_x = np_x[train_7:train_7+test_1]
  test_y = np_y[train_7:train_7+test_1]
  predict_x = np_x[train_7+test_1:]
  predict_y = y[train_7+test_1:]
  # print(9)
  return train_x, train_y, test_x, test_y, predict_x, predict_y



def getDate2(set, shuffle=True, predictTest=-60):
  load_data = requests_(set)
  x=[]
  y=[]
  total = len(load_data)

  if set.MAX_STEPS >= total: print("错误")
  for item in range(set.MAX_STEPS, total, 1):
    x.append(load_data[item - set.MAX_STEPS:item])
    y.append(load_data[item])

  np_x = np.zeros((total-set.MAX_STEPS, set.MAX_STEPS, set.FRONT_VOCAB_SIZE))
  np_y = np.zeros((total-set.MAX_STEPS, set.FRONT_VOCAB_SIZE))

  for i in range(0, len(x), 1):
    yy = y[i]
    np_y[i][yy] = 1
    for j in range(0, len(x[i]), 1):
      xx = x[i][j]
      np_x[i][j][xx] = 1

  # 0.7训练。0.3测试。 
  train_data_rate = 0.7
  train_7 = int(train_data_rate * len(x))
  # test_1 = int(0.2 * len(x))
  # 打乱训练数据
  # if shuffle:
  #   random_seed = int(time.time())
  #   # 使用相同的随机数种子，保证x和y的一一对应没有被破坏
  #   np.random.seed(random_seed)
  #   np.random.shuffle(np_x)
  #   np.random.seed(random_seed)
  #   np.random.shuffle(np_y)

  train_x = np_x[:train_7]
  train_y = np_y[:train_7]
  test_x = np_x[train_7:predictTest]
  test_y = np_y[train_7:predictTest]
  predict_x = np_x[predictTest:]
  predict_y = y[predictTest:]
  # print(9)
  return {
    "train_x":train_x,
    "train_y":train_y,
    "test_x":test_x,
    "test_y":test_y,
    "predict_x":predict_x,
    "predict_y":predict_y
    }


def authenticPredictData(set):
  """ 获取真实的时候的预测数据
   """
  load_data = []
  issueNo_ = []
  try:
    resp = requests.get(set.LOTTO_DOWNLOAD_URL)
    if resp.status_code == 200:
        respJson = resp.json()
        respJson.reverse()
        for i in range(len(respJson)):
          # 大小类别：0表示小，1表示大
          d = respJson[i]
          if d["five"] > 4:
            load_data.append(1)
          else:
            load_data.append(0)
          # load_data.append(respJson[i]["five"])
          issueNo_.append(respJson[i]["issueNo"])

        x=[load_data[-set.MAX_STEPS:]]
        issueNo=issueNo_[-set.MAX_STEPS:]
        total = len(load_data)
        if set.MAX_STEPS > total: print("错误")
        np_x = np_xFn(set, x)
        return {
          "predict_x": np_x,
          "issueNo": issueNo,
          "issueNoFive": load_data[-1:][0], # 最新期的值
          }
    else:
      raise Exception('获取数据失败！')
  except Exception as e:
    print(e)
    return None


def np_xFn(set, x):
  np_x = np.zeros((len(x), set.MAX_STEPS, set.FRONT_VOCAB_SIZE))
  for i in range(0, len(x), 1):
    for j in range(0, len(x[i]), 1):
      xx = x[i][j]
      np_x[i][j][xx] = 1
  return np_x

if __name__ == '__main__':
  set = Setting()
  # dd = getDate(set)
  train_x, train_y, test_x, test_y, predict_x, predict_y = getDate(set)
  # print(train_x, train_y, test_x, test_y, predict_x, predict_y)
  